from flask_restful import Resource, fields, marshal_with, reqparse
from app.models import User
from flask import current_app

resource_fields = {
    'username': fields.String,
    'nickname': fields.String,
    'last_login_at': fields.DateTime()
}

list_fields = {
    'data': fields.List(fields.Nested(resource_fields)),
    'pageCount': fields.String,
    'currentPage': fields.String
}


users_list_parser = reqparse.RequestParser()
users_list_parser.add_argument('page', type=int, help='必须是数字', default=1)


class Users(Resource):
    @marshal_with(resource_fields)
    def get(self, id):
        user = User.query.get(id)
        return user


class UsersList(Resource):
    @marshal_with(list_fields)
    def get(self):
        args = users_list_parser.parse_args()
        data = User.query.paginate(args['page'], current_app.config['POST_PRE_PAGE'])
        resp = {
            'data': data.items,
            'pageCount': data.pages,
            'currentPage': '1'
        }
        return resp
